/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.dto.SaveElevatorStructureRelationDTO;
import org.springblade.modules.repair.entity.Elevator;
import org.springblade.modules.repair.entity.ElevatorPartsStructureTemplate;
import org.springblade.modules.repair.entity.ElevatorPartsStructureTemplateRelation;
import org.springblade.modules.repair.service.IElevatorPartsStructureTemplateService;
import org.springblade.modules.repair.service.IElevatorService;
import org.springblade.modules.repair.mapper.ElevatorPartsStructureTemplateRelationMapper;
import org.springblade.modules.repair.service.IElevatorPartsStructureTemplateRelationService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.repair.vo.ElevatorSelectVO;
import org.springblade.modules.repair.vo.ElevatorSimpleInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 电梯配件结构模板关联 服务实现类
 *
 * @author ysq
 * @since 2024-09-04
 */
@Service
public class ElevatorPartsStructureTemplateRelationServiceImpl extends BaseServiceImpl<ElevatorPartsStructureTemplateRelationMapper, ElevatorPartsStructureTemplateRelation> implements IElevatorPartsStructureTemplateRelationService {


	@Lazy
	@Autowired
	private IElevatorPartsStructureTemplateService elevatorPartsStructureTemplateService;
	@Autowired
	private IElevatorService elevatorService;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean customSaveOrEdit(ElevatorPartsStructureTemplateRelation elevatorPartsStructureTemplateRelation) {
		if (Func.isAnyBlank(elevatorPartsStructureTemplateRelation.getCategoryArrIds(), elevatorPartsStructureTemplateRelation.getCategoryArrNames())) {
			throw new ServiceException("类别属性不能为空");
		}

		ElevatorPartsStructureTemplateRelation oldRelation = getByElevatorId(elevatorPartsStructureTemplateRelation.getElevatorId());
		if (Func.isNull(oldRelation)) {
			oldRelation = new ElevatorPartsStructureTemplateRelation();
			oldRelation.setElevatorId(elevatorPartsStructureTemplateRelation.getElevatorId());
		}

		// 如果填写完整
		if (elevatorPartsStructureTemplateRelation.getIsIntegrity()) {
			Long templateId = elevatorPartsStructureTemplateService.checkRepeat(oldRelation.getStructureTemplateId(), elevatorPartsStructureTemplateRelation.getCategoryArrIds());
			if (Func.isNull(templateId)) {
				// 新增电梯结构模板
				templateId = this.addTemplate(elevatorPartsStructureTemplateRelation.getElevatorId(), elevatorPartsStructureTemplateRelation.getCategoryArrIds(), elevatorPartsStructureTemplateRelation.getCategoryArrNames());
			}
			oldRelation.setStructureTemplateId(templateId);
		} else {
			oldRelation.setStructureTemplateId(null);
		}

		oldRelation.setCategoryArrIds(elevatorPartsStructureTemplateRelation.getCategoryArrIds());
		oldRelation.setCategoryArrNames(elevatorPartsStructureTemplateRelation.getCategoryArrNames());
		return saveOrUpdate(oldRelation);
	}

	@Override
	public ElevatorPartsStructureTemplateRelation getByElevatorId(Long elevatorId) {
		return getOne(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery().eq(ElevatorPartsStructureTemplateRelation::getElevatorId, elevatorId), false);
	}

	/**
	 * 新增电梯结构模板
	 * @param elevatorId 电梯id
	 * @param categoryArrIds 类别属性id
	 * @param categoryArrNames 类别属性名称
	 * @return 结构模板
	 */
	private Long addTemplate(Long elevatorId, String categoryArrIds, String categoryArrNames) {
		ElevatorPartsStructureTemplate newTemplate = new ElevatorPartsStructureTemplate();
		newTemplate.setName(categoryArrNames);
		newTemplate.setCategoryArrIds(categoryArrIds);
		newTemplate.setCategoryArrNames(categoryArrNames);

		String modeName = elevatorService.getModeNameByElevatorId(elevatorId);
		if (Func.equalsSafe(modeName, "自动人行道") || Func.equalsSafe(modeName, "自动扶梯")) {
			newTemplate.setElevatorType(1);
		} else {
			newTemplate.setElevatorType(0);
		}

		boolean res = elevatorPartsStructureTemplateService.save(newTemplate);
		if (!res) {
			throw new ServiceException("新增结构模板失败");
		}

		return newTemplate.getId();
	}

	@Override
	public List<ElevatorSimpleInfoVO> getAllowRelationElevatorList(Long elevatorId) {
		Elevator elevator = elevatorService.getById(elevatorId);
		if (Func.isEmpty(elevator)) {
			throw new ServiceException("电梯不存在");
		}
		ElevatorPartsStructureTemplateRelation template = this.getByElevatorId(elevatorId);
		if (Func.isEmpty(template) || Func.isEmpty(template.getStructureTemplateId())) {
			throw new ServiceException("该电梯未关联电梯结构模板");
		}

		// 查询项目下的所有电梯
		List<ElevatorSimpleInfoVO> allElevatorList = elevatorService.getListByBuildingId(elevator.getBuildingId());

		// 排除本身
		return allElevatorList.stream().filter(item -> !item.getElevatorId().equals(elevatorId)).collect(Collectors.toList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean relationToStructureTemplate(SaveElevatorStructureRelationDTO param) {
		if (Func.isNull(param.getStructureTemplateId())) {
			throw new ServiceException("模板id不能为空");
		}
		ElevatorPartsStructureTemplate template = elevatorPartsStructureTemplateService.getById(param.getStructureTemplateId());
		if (Func.isNull(template)) {
			throw new ServiceException("模板不存在");
		}

		// 删除原本关联
		if (Func.isNotEmpty(param.getRemoveElevatorIds())) {
			baseMapper.delete(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery()
				.eq(ElevatorPartsStructureTemplateRelation::getStructureTemplateId, param.getStructureTemplateId())
				.in(ElevatorPartsStructureTemplateRelation::getElevatorId, param.getRemoveElevatorIds()));
		}

		if (Func.isNotEmpty(param.getElevatorIds())) {
			int checkCount = count(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery().in(ElevatorPartsStructureTemplateRelation::getElevatorId, param.getElevatorIds()));
			if (checkCount > 0) {
				throw new ServiceException("存在电梯已关联模板，请不要重复关联");
			}

			List<ElevatorPartsStructureTemplateRelation> saveList = new ArrayList<>();
			for (Long elevatorId : param.getElevatorIds()) {
				ElevatorPartsStructureTemplateRelation item = new ElevatorPartsStructureTemplateRelation();
				item.setStructureTemplateId(param.getStructureTemplateId());
				item.setElevatorId(elevatorId);
				item.setCategoryArrIds(template.getCategoryArrIds());
				item.setCategoryArrNames(template.getCategoryArrNames());
				saveList.add(item);
			}

			return this.saveBatch(saveList);
		}

		return true;
	}

	@Override
	public Long getSameStructureCount(Long elevatorId) {
		Elevator elevator = elevatorService.getById(elevatorId);
		if (Func.isEmpty(elevator)) {
			throw new ServiceException("电梯不存在");
		}
		ElevatorPartsStructureTemplateRelation template = this.getByElevatorId(elevatorId);
		if (Func.isEmpty(template) || Func.isEmpty(template.getStructureTemplateId())) {
			return 0L;
		}

		List<Long> sameStructureElevatorIds = this.list(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery()
			.eq(ElevatorPartsStructureTemplateRelation::getStructureTemplateId, template.getStructureTemplateId()))
			.stream().map(ElevatorPartsStructureTemplateRelation::getElevatorId).collect(Collectors.toList());

		// 查询项目下的所有电梯
		List<ElevatorSimpleInfoVO> allElevatorList = elevatorService.getListByBuildingId(elevator.getBuildingId());
		return allElevatorList.stream().filter(item -> sameStructureElevatorIds.contains(item.getElevatorId())).count();
	}
}
